import router, {transformRoutes, devRoutes} from './index.js'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {useAppStore} from "@/store/app.js";
import AuthAPI from '@/api/auth/index.js'
import {convertMenuToTree} from "@/views/setting/menu/common.js";

NProgress.configure({showSpinner: false})

const whiteList = ['/login', '/404'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
    const appStore = useAppStore();
    NProgress.start()
    console.log(`token: ${appStore.token} = from: ${from.fullPath} -> to: ${to.fullPath}`);
    document.title = to.meta?.title || ''
    if (appStore.token) {
        if (to.path === "/login") {
            next({path: "/", replace: true});
        } else if (appStore.userInfo.id > 0) {
            to.matched.length === 0 ? next({path: '404'}) : next()
        } else {
            const info = await AuthAPI.getInfo()
            let routers = transformRoutes(convertMenuToTree(info.menus))
            routers = routers.concat(devRoutes)
            routers.filter(v => v.meta.type !== 4).forEach(item => router.addRoute(item))
            appStore.routers = routers;
            appStore.userInfo.id = info.id
            appStore.userInfo.username = info.nickname
            appStore.userInfo.role_name = info.role_name
            next({...to, replace: true})
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            redirectToLogin(to, next)
        }
    }
})

function redirectToLogin(to, next) {
    const params = new URLSearchParams(to.query);
    const queryString = params.toString();
    const redirect = queryString ? `${to.path}?${queryString}` : to.path;
    next(`/login?redirect=${encodeURIComponent(redirect)}`);
}

router.afterEach(() => {
    NProgress.done()
})
